<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NButton,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NPopconfirm,
  NTreeSelect,
  useMessage,
  NTag, NFlex, NCard, NAvatar, NSwitch, NImage, NUpload
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import TheIcon from '@/components/icon/TheIcon.vue'

import {getToken, renderIcon} from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'
import {forEach} from "lodash-es";
import default_image from "@/assets/images/mz.jpg";

defineOptions({ name: '评分规则' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE

const message = useMessage()

const {
  modalVisible,
  modalTitle,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '评分规则',
  initForm: {},
  doCreate: api.createExamScore,
  doUpdate: api.updateExamScore,
  doDelete: api.deleteExamScore,
  refresh: () => $table.value?.handlerefresh(),
})
const data = reactive({
  token: getToken(),
  uploadAction: base_path+'api/exams/exam/file',
  customer_level: [],
  routers: [
    {
      name: '',
      type: '',
      num: '',
    },
  ],
  ExamData: [],
})
const deptOption = ref([])
const isDisabled = ref(false)
const onCreate = () => {
  return {
    exam_id: '',
    name: '',
    rate: '',
    score_min: '',
    score_max: '',
    picture: '',
  }
}
onMounted(() => {


  api.getListExam().then((res) => (data.ExamData = res.data))
  $table.value?.handleSearch()
})
async function getcosutomer_level() {
  let ret = await api.getCustomerLevel()
  data.customer_level = ret.data
}
async function hanbeSumit() {
  console.log(1, 'modalForm1')
}

const deptRules = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: ['input', 'blur', 'change'],
    },
  ],
}

async function addDepts() {
  isDisabled.value = false
  handleAdd()
}

function get_level_name(id){
  let ret = ""
  data.customer_level.forEach((item) => {
    if (item.value === id) {
      ret = item.label
    }
  })
  return ret
}

const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '试卷名称',
    key: 'title',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '名称',
    key: 'name',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '分数小值',
    key: 'score_min',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '分数大值',
    key: 'score_max',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '创建时间',
    key: 'created_at',
    align: 'center',
    width: 'auto',
    ellipsis: { tooltip: true },
  },
  {
    title: '操作',
    key: 'actions',
    width: 'auto',
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
            h(
                NButton,
                {
                  size: 'small',
                  type: 'primary',
                  style: 'margin-right: 8px;',
                  onClick: () => {
                    handleEdit(row)
                    if(!row.picture){
                      modalForm.value.picture = []
                    }
                  },
                },
                {
                  default: () => '编辑',
                  icon: renderIcon('material-symbols:edit', { size: 16 }),
                }
            ),
            [[vPermission, 'post/api/content/category/update']]
        ),
        h(
            NPopconfirm,
            {
              onPositiveClick: () => handleDelete({ data_id: row.id }, false),
              onNegativeClick: () => {},
            },
            {
              trigger: () =>
                  withDirectives(
                      h(
                          NButton,
                          {
                            size: 'small',
                            type: 'error',
                          },
                          {
                            default: () => '删除',
                            icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                          }
                      ),
                      [[vPermission, 'delete/api/content/category/delete']]
                  ),
              default: () => h('div', {}, '确定删除该数据吗?'),
            }
        ),
      ]
    },
  },
]

const handleFinish = ({ file, event }) => {
  let data = (event?.target).response
  data = JSON.parse(data)
  if (data.code === 200) {
    file.url = data.data.url
    message.success('上传成功')
  } else {
    message.error(data.data)
  }

  return file
}


// 修改用户禁用状态
async function handleUpdateDisable(row) {
  if (!row.id) return
  row.publishing = true
  row.state = row.state === false
  row.publishing = false
  try {
    await api.updateExam(row)
    $message?.success(row.state ? '已取消禁' : '已禁用')
    $table.value?.handleSearch()
  } catch (err) {
    // 有异常恢复原来的状态
    row.state = row.state === false ? true : false
  } finally {
    row.publishing = false
  }
}

</script>

<template>
  <!-- 业务页面 -->
  <CommonPage show-footer title="评分规则">
    <template #action>
      <div>
        <NButton
            v-permission="'post/api/content/category/create'"
            class="float-right mr-15"
            type="primary"
            @click="addDepts"
        >
          <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建规则
        </NButton>
      </div>
    </template>
    <!-- 表格 -->
    <CrudTable
        ref="$table"
        v-model:query-items="queryItems"
        :columns="columns"
        :get-data="api.getExamScore"
        default-expand-all
    >
      <template #queryBar>
        <QueryBarItem label="试卷名称" :label-width="80">
          <NInput
              v-model:value="queryItems.title"
              clearable
              type="text"
              placeholder="请输入试卷名称"
              @keypress.enter="$table?.handleSearch()"
          />
        </QueryBarItem>
      </template>
    </CrudTable>

    <!-- 新增/编辑 弹窗 -->
    <CrudModal
        v-model:visible="modalVisible"
        :title="modalTitle"
        :loading="modalLoading"
        style="width: 1200px !important"
        @save="handleSave"
    >
      <NForm
          ref="modalFormRef"
          label-placement="left"
          label-align="left"
          :label-width="80"
          :model="modalForm"
          :rules="deptRules"
          @submit="hanbeSumit"
      >
        <NFormItem label="试卷名称" path="title" style="width: 100%">
          <NSelect v-model:value="modalForm.exam_id" :options="data.ExamData" clearable placeholder="请选择试卷名称" />
        </NFormItem>

        <NFormItem label="名称" path="name" style="width: 500px">
          <NInput v-model:value="modalForm.name" clearable placeholder="请输入名称" />
        </NFormItem>

        <NFormItem label="比例" path="rate" style="width: 200px">
          <NInput v-model:value="modalForm.rate" clearable placeholder="" />
        </NFormItem>

        <NFormItem label="分数小值" path="score_min" style="width: 200px">
          <NInputNumber v-model:value="modalForm.score_min" clearable placeholder="" />
        </NFormItem>

        <NFormItem label="分数大值" path="score_max" style="width: 200px">
          <NInputNumber v-model:value="modalForm.score_max" clearable placeholder="" />
        </NFormItem>

        <NFormItem label="图片" path="picture" style="width: 100%">
          <NUpload
              :action="data.uploadAction"
              :headers="{ token: data.token }"
              multiple
              list-type="image-card"
              @finish="handleFinish"
              v-model:file-list="modalForm.picture"
          >
          </NUpload>
        </NFormItem>

      </NForm>
    </CrudModal>
  </CommonPage>
</template>
